package com.ckk.cloud.orderpayment.lb.impl;

import com.ckk.cloud.orderpayment.lb.LoadBlance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 陈昆昆
 * @version 1.0
 * @date 2020/6/16 12:51
 */
@Component
public class LoadBlanceImpl implements LoadBlance {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getindex(){
        int current;
        int next;
        do {
            //先赋值
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!atomicInteger.compareAndSet(current, next));
        System.out.println("当前访问的次数是"+next);
        return next;
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> instanceList) {
        int index = getindex() % instanceList.size();
        return instanceList.get(index);
    }
}
